package org.example.product.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.core.utils.PageUtils;
import org.example.core.utils.R;
import org.example.product.dao.AttributeDao;
import org.example.product.entity.AttributeEntity;
import org.example.product.service.AttributeService;
import org.example.product.service.AttributeCategoryService;
import org.example.product.service.SkuAttributeService;
import org.example.product.service.SpuAttributeService;
import org.example.product.vo.AttributeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Service("attributeService")
public class AttributeServiceImpl implements AttributeService {

    @Autowired
    private AttributeDao attributeDao;
    @Autowired
    private AttributeCategoryService categoryAttributeService;
    @Autowired
    private SpuAttributeService spuAttributeService;
    @Autowired
    private SkuAttributeService skuAttributeService;

    // 获取属性列表
    @Override
    public PageUtils queryAttrList(Integer pageNum, Integer pageSize, String name, Long categoryId, Integer type) {
        // 分页
        PageHelper.startPage(pageNum,pageSize);
        List<Long> attrIds = null;
        if (categoryId != 0){
            attrIds = categoryAttributeService.queryAttrIdByCategoryId(categoryId);
            if (attrIds.isEmpty()){
                return new PageUtils(new PageInfo<>());
            }
        }
        List<AttributeEntity> entities = attributeDao.getAttrList(name, type, attrIds);
        return new PageUtils(new PageInfo<>(entities));
    }

    // 根据id或者属性信息
    @Override
    public AttributeEntity queryAttributeInfoById(Long attributeId) {
        return attributeDao.getAttrInfoById(attributeId);
    }

    // 添加属性
    @Override
    public int saveAttributeInfo(AttributeEntity attribute) {
        return attributeDao.addAttributeInfo(attribute);
    }

    // 修改属性信息
    @Override
    public int editAttributeInfo(AttributeEntity attribute) {
        return attributeDao.updateAttributeInfo(attribute);
    }

    // 根据分类id获取到属性集合
    @Override
    public List<AttributeVo> queryAttrsByCategoryId(Long categoryId, Integer type) {
        return attributeDao.getAttrsByCategoryId(categoryId,type);
    }

    @Override
    public R<?> deletes(List<Long> ids) {
        // 是否关联了spu
        if (spuAttributeService.isSpuAttrByAttrIds(ids)){
            return R.error("属性关联了spu不能删除");
        }
        // 是否关联了sku
        if (skuAttributeService.isSkuAttrByAttrIds(ids)){
            return R.error("属性关联了sku不能删除");
        }
        // 删除关联的分类
        categoryAttributeService.deleteByAttrIds(ids);
        // 删除属性
        return attributeDao.deletes(ids)>0? R.ok():R.error();
    }
}